<!-- eslint-disable vue/require-default-prop -->
<template>
  <el-dialog
    :title="livestock('羊只选择') + titleName"
    :visible="true"
    style="margin-top: 0px !important"
    :before-close="back"
  >
    <baseMainSlot :show-tab="true" :show-btn-box="false">
      <template v-slot:search-box>
        <SearchBox
          :renovate="true"
          :refresh="true"
          :search-show=" true"
          @search="search"
          @refresh="releave"
        >
          <div class="common-search-item yueling">
            <div class="label">月龄区间:</div>
            <div class="input">
              <el-input
                v-model="endTime"
                :min="0"
                type="number"
                placeholder="开始时间"
                @change="endTime=endTime.replace(/[^\d]+/g,'')"
              />
            </div>
            <div class="input">
              <el-input
                v-model="startTime"
                type="number"
                :min="0"
                placeholder="结束时间"
                @change="startTime=startTime.replace(/[^\d]+/g,'')"
              />
            </div>
          </div>
          <div v-if="needFlag" class="common-search-item">
            <div class="label">在群状态:</div>
            <div class="input">
              <el-select v-model="groupFlag" placeholder="选择在群状态" @change="getTableDataList">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
        </SearchBox>
      </template>
      <template v-slot:table-box>
        <el-table
          ref="sheepSelectData"
          v-loading="loading"
          :data="sheepSelectData"
          stripe
          select-on-indeterminate
          border
          :empty-text="loading ? '搜索中' : '暂无数据'"
          :row-key="getRowKeys"
          @select="select"
          @selection-change="selectionChange"
        >
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column
            v-for="(item,index) in tableDataList"
            :key="index"
            :prop="item.porp"
            :label="item.name"
            :min-width="item.minWidth"
            :reserve-selection="true"
          >
            <template v-if="scope.row.sheepNo" slot-scope="scope">
              <span
                v-if="item.porp === 'eleEarLabel'"
              >{{ scope.row.eleEarLabel || livestock('该羊无电子耳标') }}</span>
              <span v-else>{{ scope.row[item.porp] }}</span>
            </template>
            <template v-if="!item.notSearch" #header>
              <TypePopover
                v-if="tableUpStauts === 1"
                :column-index="index"
                :column="item"
                :filter-options="item.typeObj.list"
                :filter-name="item.typeObj.listName"
                :table-up-stauts="tableUpStauts"
                @tableUpdate="tableUpdate($event, item.name)"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="selectType === 'single'"
            label="操作"
            min-width="60"
          >
            <template v-if="scope.row.sheepNo" slot-scope="scope">
              <el-button
                type="text"
                class="text-btn-cursor"
                size="small"
                @click.stop="select(scope.row)"
              >
                <i class="el-icon-edit-outline"></i>选择
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            v-if="selectType === 'more'"
            type="selection"
            :selectable="row => !!row.sheepNo"
            :reserve-selection="true"
            width="120"
          />
        </el-table>
        <div class="dialog-footer">
          <Pagination
            :page-size="pageSize"
            :current-page="currentPage"
            :total-size="totalSize"
            @changePageSize="changePageSize"
            @changeCurrentPage="changeCurrentPage"
          />
          <div class="select-button">
            <el-button
              v-if="selectType === 'more'"
              class="zh-button-two"
              type="primary"
              @click="commit()"
            >确认选择</el-button>
            <el-button class="zh-button-one" @click="back()">取消</el-button>
          </div>
        </div>
      </template>
    </baseMainSlot>
  </el-dialog>
</template>
<script>
import baseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import Pagination from "@/components/Pagination";
import SearchBox from "@/components/SearchBox";
import TypePopover from "@/components/ZnFilterTable/typePopover.vue";
import { mymixin } from "@/utils/mixins";
import SheepInfoApi from "@/api/basic-info-manage/sheep-management/sheep-information";
import facilityApi from "@/api/basic-info-manage/fence-management";
import sheepBreedApi from "@/api/basic-info-manage/breed-varieties-management";
export default {
  name: "SheepSelect",
  components: {
    baseMainSlot,
    Pagination,
    SearchBox,
    TypePopover
  },
  mixins: [mymixin],
  props: {
    portableFields: {
      type: Array,
      default: () => []
    },
    needFlag: {
      type: Boolean,
      default: false
    },
    selectType: {
      type: String,
      default: "single"
    }, // 区分选择类型(例子：选择公羊，选择母羊，单选，多选)
    initialParameters: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      // doorList: [],
      fenceList: [],
      sheepSelectData: [],
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      loading: true,
      groupFlag: true,
      noList: [],
      startTime: "",
      endTime: "",
      buildingNo: undefined, // 栋舍编号
      columnNo: undefined, // 栏舍编号
      spread: [],
      options: [
        { value: true, label: "在群" },
        { value: false, label: "离群" }
      ],
      sheepSource: [
        { name: "本场出生", value: "本场出生" },
        { name: "国内引进", value: "国内引进" },
        { name: "国外引进", value: "国外引进" }
      ],
      tableDataList: [
        {
          type: "input",
          porp: "earLabel",
          typeObj: {},
          name: "耳标"
        },
        {
          type: "input",
          porp: "eleEarLabel",
          typeObj: {},
          name: "电子耳标",
          minWidth: "120"
        },
        {
          type: "Select",
          porp: "buildingName",
          selectValue: "buildingNo",
          typeObj: {},
          name: "栋舍"
          // notSearch: true
        },
        {
          type: "Select",
          porp: "columnName",
          selectValue: "columnNo",
          typeObj: {},
          name: "栏舍"
          // notSearch: true
        },
        {
          type: "Select",
          porp: "gender",
          selectValue: "gender",
          typeObj: {
            list: [
              { name: "公", value: "公" },
              { name: "母", value: "母" }
            ]
          },
          name: "性别",
          notSearch: !!this.initialParameters.gender
        },
        {
          type: "Select", // input Select Checkbox date
          porp: "reproductiveStatus",
          typeObj: {
            list: [
              { name: "已配未检", value: "已配未检" },
              { name: "初检-", value: "初检-" },
              { name: "初检+", value: "初检+" },
              { name: "复检-", value: "复检-" },
              { name: "复检+", value: "复检+" },
              { name: "流产未配", value: "流产未配" },
              { name: "产后未配", value: "产后未配" },
              { name: "育成", value: "育成" },
              { name: "出生", value: "出生" },
              { name: "已投放", value: "已投放" },
              { name: "未投放", value: "未投放" }
            ],
            listName: ["name", "value"]
          },
          minWidth: "100",
          name: "繁育状态"
        },
        {
          type: "date",
          porp: "birthday",
          typeObj: {},
          name: "出生日期"
        },
        // {
        //   type: "input",
        //   porp: "eleEarLabel",
        //   typeObj: {},
        //   name: "月龄"
        // }
        {
          type: "Select",
          porp: "source",
          selectValue: "source",
          typeObj: {
            list: [
              { name: "本场出生", value: "本场出生" },
              { name: "国内引进", value: "国内引进" },
              { name: "国外引进", value: "国外引进" }
            ]
          },
          name: "来源"
        }
      ]
    };
  },
  computed: {
    titleName: function() {
      return this.selectType === "more" ? "(多选)" : "(单选)";
    }
  },
  created() {
    this.portableFields.forEach(item => {
      this.tableDataList.push(item);
    });
    this.currentPage = 1;
    this.pageSize = 10;
    this.getTableDataList();
    this.getDoor();
    this.getFence();
    this.getBreedList();
  },
  methods: {
    selectionChange(e) {
      this.spread = e;
    },
    // 获取所有品种
    getBreedList() {
      sheepBreedApi.getByCondition({}).then(res => {
        if (res.code === 1) {
          let list = [];
          res.data.forEach(item => {
            list.push({
              name: item.breedVarietyName,
              value: item.breedVarietyNo
            });
          });
          this.tableDataList.forEach((item, index) => {
            if (item.porp === "plantVarietyName") {
              this.$set(this.tableDataList[index], "typeObj", { list });
            }
          });
        }
      });
    },
    // 刷新
    releave() {
      this.buildingNo = "";
      this.columnNo = "";
      this.startTime = "";
      this.endTime = "";
      this.searchObj = {};
      this.getTableDataList();
      this.$refs.sheepSelectData.clearSelection();
    },
    // 跨页选择
    getRowKeys(row) {
      return row.sheepNo;
    },
    selectable(row) {
      return !!row.earLabel;
    },

    getbothDay(months) {
      if (months) {
        var date = new Date();
        date.setMonth(date.getMonth() - months);
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return (
          date.getFullYear() +
          "-" +
          (month < 10 ? "0" + month : month) +
          "-" +
          (day < 10 ? "0" + day : day)
        );
      } else {
        return undefined;
      }
    },
    // 获取栏舍
    // getFence(e) {
    //   this.columnNo = "";
    //   this.fenceList = [];
    //   facilityApi
    //     .conditionQuery({
    //       facilityType: "羊栏",
    //       parentNo: e,
    //       status: 0
    //     })
    //     .then(res => {
    //       if (res.code === 1) {
    //         this.fenceList = res.data;
    //       }
    //     });
    // },
    getFence(e = undefined) {
      facilityApi
        .conditionQuery({ status: 0, facilityType: "羊栏", parentNo: e })
        .then(res => {
          this.$set(this.tableDataList[3], "typeObj", {
            list: res.data,
            listName: ["facilityName", "facilityNo"]
          });
        });
    },
    async tableUpdatePlus(data) {
      if (data.tagname === "栋舍") {
        this.getFence(data?.value);
      }
    },
    // 获取所有栋舍
    getDoor() {
      facilityApi
        .conditionQuery({ facilityType: "羊舍", status: 0 })
        .then(res => {
          if (res.code === 1) {
            this.$set(this.tableDataList[2], "typeObj", {
              list: res.data,
              listName: ["facilityName", "facilityNo"]
            });
          }
        });
    },
    // 获取羊只列表
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          buildingNo: this.buildingNo,
          columnNo: this.columnNo,
          groupFlag: this.groupFlag,
          startDate: this.getbothDay(this.startTime),
          endDate: this.getbothDay(this.endTime),
          sheepType: !this.FatteningStatus ? "育肥羊" : undefined,
          ...this.initialParameters,
          ...this.searchObj
        }
      };
      SheepInfoApi.getList(params).then(res => {
        if (res.code === 1) {
          if (res.data.content.length === 0) {
            this.$message.warning(this.livestock('"未搜索到符合条件的羊只"'));
          }
          this.sheepSelectData = JSON.parse(
            this.livestock(JSON.stringify(res.data.content))
          );
          this.totalSize = res.data.totalElements;
          this.addblankmet();
          this.loading = false;
          // this.getSelectData();
        }
      });
    },
    // 数组对象去重
    arrayObjDup(e) {
      if (e.length > 1) {
        let map = new Map();
        for (let item of e) {
          map.set(item.sheepNo, item);
        }
        return [...map.values()];
      } else {
        return e;
      }
    },
    // 获取跨页回响数据
    getSelectData() {
      if (this.spread.length > 0) {
        this.spread = this.arrayObjDup(this.spread); // 去重
        this.sheepSelectData.forEach(item => {
          this.spread.forEach(item1 => {
            if (item.sheepNo === item1.sheepNo) {
              this.$nextTick(() => {
                this.$refs.sheepSelectData.toggleRowSelection(item, true);
              });
            }
          });
        });
      }
    },
    select(e) {
      // e选中的值 a点击的那个值
      // if (this.selectType === "more") {
      //   let index = this.spread.findIndex(item => item.sheepNo === a.sheepNo);
      //   if (index !== -1) {
      //     this.spread.splice(index, 1);
      //   } else {
      //     this.spread.push(a);
      //   }
      // }
      if (this.selectType === "single") {
        this.$emit("selectedSheep", e, this.selectType);
        this.back();
      }
    },
    // 传递被选中的羊只
    commit() {
      this.$emit("selectedSheep", this.spread, this.selectType);
      this.back();
    },
    close() {
      this.back();
    },
    // 关闭选择羊只界面
    back() {
      this.$emit("closeSheepSelect");
      this.sheepSelectData = [];
    },
    // 填充空白行
    addblankmet() {
      let havline = this.sheepSelectData.length % this.pageSize;
      if (
        this.sheepSelectData.length < this.pageSize &&
        this.sheepSelectData.length !== 0
      ) {
        if (havline < this.pageSize) {
          const remain = this.pageSize - havline;
          for (var i = 0; i < remain; i++) {
            this.sheepSelectData.push({
              index: i + this.sheepSelectData.length - 1
            });
          }
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .search-content .search-btn {
  width: 160px;
}
::v-deep {
  .el-dialog {
    width: 86%;
    height: 93%;
    margin-top: 0 !important;
  }
  // .table-content {
  //   overflow: hidden;
  // }
  .el-dialog__body {
    padding: 10px 15px;
    max-height: 90% !important;
    .el-table--medium td .cell {
      min-height: 38px;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      -webkit-box-pack: center;
      -ms-flex-pack: center;
      justify-content: center;
    }
    .el-table--medium td {
      padding: 2px 0;
    }
    .dialog-footer {
      display: flex;
      flex-direction: row !important;
      justify-content: flex-end !important;
      margin-top: 10px;
      align-items: center !important;
      background-color: unset !important;
      .select-button {
        margin-left: 30px;
      }
    }
  }
  .staff-manage .btn-bot {
    height: 0px;
  }
  .el-dialog .el-dialog__body .el-table th.is-leaf {
    border-color: $inputBorderColor !important;
  }
  .el-dialog .el-dialog__body .el-table th {
    background-color: $tableHeaderColor !important;
    color: #fff !important;
    .cell {
      color: #fff !important;
    }
  }
  .el-dialog .el-dialog__body .el-table--border {
    border-radius: unset !important;
  }

  .el-dialog .el-dialog__body .el-table {
    max-height: 100% !important;
  }
  .staff-manage .search-box {
    margin-bottom: unset !important;
  }
  .pagination {
    position: unset;
    // bottom: 10px;
    right: 200px;
  }
}
.yueling {
  width: 30% !important;
}
.common-search-item {
  justify-content: flex-end;
}
.showRight {
  text-align: right;
  margin-left: auto;
  font-size: 16px;
}
.showRight1:hover {
  font-size: 20px;
  color: $hamburgFontActiveColor;
}
::v-deep .staff-manage .table-box .table-content {
  position: unset !important;
}
</style>
import { mymixin } from '@/utils/mymixin';
